package com.ruoyi.certificate.service.impl;

import com.ruoyi.certificate.domain.DidCertificate;
import com.ruoyi.certificate.mapper.DidCertificateMapper;
import com.ruoyi.certificate.service.IDidCertificateService;
import com.ruoyi.certificate.util.CertificateUtil;

import javax.annotation.Resource;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.cert.X509Certificate;
import java.util.Base64;
import java.util.List;

public class DidCertificateServiceImpl implements IDidCertificateService {

    @Resource
    private DidCertificateMapper certificateMapper;

    @Override
    public DidCertificate generateCertificate(Long userId, String publicKey) {
        try {
            // 1. 先生成一对新的RSA密钥对（也可以直接用传入的公钥）
            KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
            keyGen.initialize(2048);
            KeyPair keyPair = keyGen.generateKeyPair();

            // 2. 使用工具类生成证书
            X509Certificate cert = CertificateUtil.generateCertificate(keyPair, "User-" + userId);

            // 3. 转换为 PEM 格式字符串
            String pem = "-----BEGIN CERTIFICATE-----\n" +
                    Base64.getMimeEncoder(64, new byte[]{'\n'})
                            .encodeToString(cert.getEncoded()) +
                    "\n-----END CERTIFICATE-----";

            DidCertificate dc = new DidCertificate();
            dc.setUserId(userId);
            dc.setPublicKey(Base64.getEncoder().encodeToString(keyPair.getPublic().getEncoded()));
            dc.setCertificate(pem);
            dc.setStatus("valid");

            certificateMapper.insertCertificate(dc);

            return dc;
        } catch (Exception e) {
            throw new RuntimeException("证书生成失败", e);
        }
    }

    @Override
    public DidCertificate getCertificate(Long id) {
        return certificateMapper.selectById(id);
    }

    @Override
    public List<DidCertificate> listCertificates() {
        return certificateMapper.selectAll();
    }

    @Override
    public boolean revokeCertificate(Long id) {
        return certificateMapper.updateStatus(id, "revoked") > 0;
    }
}
